<template>
  <div class="room-lobby">
    <!-- 房间信息 -->
    <div class="room-header">
      <h2>{{ roomData.name }}</h2>
      <div class="room-id">房间号: {{ roomData.id }}</div>
    </div>

    <!-- 玩家列表 -->
    <div class="players-section">
      <h3>玩家 ({{ playersInRoom.length }}/3)</h3>
      <div class="players-grid">
        <div 
          v-for="(player, index) in playersSlots" 
          :key="index"
          class="player-slot"
          :class="{ 
            'occupied': player, 
            'host': player?.id === roomData.hostId,
            'ai-player': player?.isAI,
            'ready': player?.isReady,
            'self': player?.id === playerId
          }"
        >
          <div v-if="player" class="player-info">
            <div class="player-avatar">
              <span v-if="player.isAI">🤖</span>
              <span v-else-if="player.id === roomData.hostId">👑</span>
              <span v-else>👤</span>
            </div>
            <div class="player-name">{{ player.name }}</div>
            <div v-if="!player.isAI && player.id !== roomData.hostId" class="player-status">
              {{ player.isReady ? '已准备' : '未准备' }}
            </div>
            <div v-else-if="player.isAI" class="player-status ai-status">
              AI玩家
            </div>
            <div v-else class="player-status host-status">
              房主
            </div>
          </div>
          <div v-else class="empty-slot">
            <div class="slot-icon">⚪</div>
            <div class="slot-text">等待玩家</div>
            <!-- AI补位按钮 -->
            <button 
              v-if="isHost && playersInRoom.length < 3" 
              class="add-ai-btn"
              @click="addAI"
              :disabled="addingAI"
            >
              {{ addingAI ? '添加中...' : '+ AI补位' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作区域 -->
    <div class="actions-section">

      <!-- 房主的AI补位按钮 -->
      <button 
        v-if="isHost && playersInRoom.length < 3"
        class="btn btn-ai" 
        @click="addAI"
        :disabled="addingAI"
      >
        {{ addingAI ? '添加AI中...' : '🤖 添加AI补位' }}
      </button>

      <!-- 非房主玩家的准备按钮 -->
      <button 
        v-if="!isHost && !isPlayerReady"
        class="btn btn-ready" 
        @click="toggleReady(true)"
        :disabled="readyLoading"
      >
        {{ readyLoading ? '准备中...' : '准备' }}
      </button>
      
      <button 
        v-if="!isHost && isPlayerReady"
        class="btn btn-cancel-ready" 
        @click="toggleReady(false)"
        :disabled="readyLoading"
      >
        {{ readyLoading ? '取消中...' : '取消准备' }}
      </button>

      <!-- 房主的开始游戏按钮 -->
      <button 
        v-if="isHost"
        class="btn btn-start" 
        @click="startGame"
        :disabled="!canStartGame || startingGame"
      >
        {{ startingGame ? '启动中...' : '开始游戏' }}
      </button>

      <!-- 离开房间按钮 -->
      <button class="btn btn-leave" @click="leaveRoom" :disabled="leavingRoom">
        {{ leavingRoom ? '离开中...' : '离开房间' }}
      </button>
    </div>

    <!-- 游戏规则说明 -->
    <div class="rules-hint">
      <div class="hint-text">💡 等待所有玩家准备后即可开始游戏</div>
      <div class="hint-text">🤖 可以添加AI玩家补位，无需等待真人玩家</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useMultiplayerStore } from '../store/multiplayer.js'
import { useGameStore } from '../store/game.js'

const multiplayerStore = useMultiplayerStore()
const gameStore = useGameStore()

// 响应式状态
const readyLoading = ref(false)
const startingGame = ref(false)
const leavingRoom = ref(false)
const addingAI = ref(false)

// 计算属性
const roomData = computed(() => multiplayerStore.roomData || {})
const playersInRoom = computed(() => roomData.value.players || [])
const playerId = computed(() => multiplayerStore.playerId)
const isHost = computed(() => multiplayerStore.isHost)
const isPlayerReady = computed(() => {
  const player = playersInRoom.value.find(p => p.id === playerId.value)
  return player?.isReady || false
})

// 生成3个玩家位置的数组
const playersSlots = computed(() => {
  const slots = new Array(3).fill(null)
  playersInRoom.value.forEach(player => {
    if (player.seatIndex >= 0 && player.seatIndex < 3) {
      slots[player.seatIndex] = player
    }
  })
  return slots
})

const canStartGame = computed(() => {
  if (playersInRoom.value.length < 3) return false
  // 检查除房主和AI外的所有玩家是否都已准备
  const humanNonHostPlayers = playersInRoom.value.filter(p => 
    p.id !== roomData.value.hostId && !p.isAI
  )
  return humanNonHostPlayers.every(p => p.isReady)
})

// 方法
const toggleReady = async (ready) => {
  readyLoading.value = true
  try {
    await multiplayerStore.toggleReady(ready)
  } catch (error) {
    alert('操作失败: ' + error.message)
  }
  readyLoading.value = false
}

const startGame = async () => {
  startingGame.value = true
  try {
    // 设置游戏模式（这里不需要立即设置playing状态）
    gameStore.setGameMode('multiplayer')
    
    // 发送开始游戏请求到服务器
    await multiplayerStore.startGame()
    
    // 状态切换将由 handleGameStarted 事件触发，无需在此处理
    console.log('游戏开始请求已发送')
    
  } catch (error) {
    console.error('开始游戏失败:', error)
    alert('开始游戏失败: ' + error.message)
  }
  startingGame.value = false
}

const addAI = async () => {
  addingAI.value = true
  try {
    const result = await multiplayerStore.addAIPlayer()
    console.log('AI玩家添加成功:', result)
  } catch (error) {
    alert('添加AI玩家失败: ' + error.message)
  }
  addingAI.value = false
}

const leaveRoom = async () => {
  if (confirm('确定要离开房间吗？')) {
    leavingRoom.value = true
    try {
      await multiplayerStore.leaveRoom()
      // 返回主菜单
      gameStore.setGameStatus('menu')
    } catch (error) {
      alert('离开房间失败: ' + error.message)
    }
    leavingRoom.value = false
  }
}

// 监听房间更新事件
const setupRoomListeners = () => {
  if (multiplayerStore.socket) {
    multiplayerStore.socket.on('room_updated', (response) => {
      if (response.success) {
        multiplayerStore.roomData = response.data
        console.log('房间信息已更新:', response.data)
      }
    })
  }
}

// 页面加载时检查房间状态
onMounted(() => {
  if (!multiplayerStore.isInRoom) {
    gameStore.setGameStatus('menu')
    return
  }
  setupRoomListeners()
})

onUnmounted(() => {
  // 清理事件监听
  if (multiplayerStore.socket) {
    multiplayerStore.socket.off('room_updated')
  }
})
</script>

<style scoped>
.room-lobby {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(-45deg, #667eea, #764ba2, #f093fb, #f5576c);
  background-size: 400% 400%;
  animation: gradientShift 8s ease infinite;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

@keyframes gradientShift {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

.room-header {
  text-align: center;
  margin-bottom: 30px;
  color: white;
}

.room-header h2 {
  font-size: 28px;
  margin: 0 0 10px 0;
  text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
}

.room-id {
  font-size: 16px;
  opacity: 0.8;
  background: rgba(255, 255, 255, 0.1);
  padding: 5px 15px;
  border-radius: 15px;
  display: inline-block;
}

.players-section {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  padding: 30px;
  margin-bottom: 30px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  width: 100%;
  max-width: 600px;
}

.players-section h3 {
  color: white;
  text-align: center;
  margin: 0 0 25px 0;
  font-size: 20px;
}

.players-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.player-slot {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  padding: 20px;
  text-align: center;
  border: 2px solid transparent;
  transition: all 0.3s ease;
  min-height: 140px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.player-slot.occupied {
  border-color: rgba(255, 255, 255, 0.3);
}

.player-slot.host {
  border-color: #FFD700;
  background: rgba(255, 215, 0, 0.1);
}

.player-slot.ai-player {
  border-color: #4ECDC4;
  background: rgba(78, 205, 196, 0.1);
}

.player-slot.ready {
  border-color: #2ECC71;
  background: rgba(46, 204, 113, 0.1);
}

.player-slot.self {
  border-color: #E74C3C;
  background: rgba(231, 76, 60, 0.1);
}

.player-info {
  color: white;
}

.player-avatar {
  font-size: 32px;
  margin-bottom: 10px;
}

.player-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.player-status {
  font-size: 12px;
  padding: 3px 8px;
  border-radius: 10px;
  display: inline-block;
}

.ai-status {
  background: rgba(78, 205, 196, 0.3);
}

.host-status {
  background: rgba(255, 215, 0, 0.3);
}

.empty-slot {
  color: rgba(255, 255, 255, 0.6);
}

.slot-icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.slot-text {
  font-size: 14px;
  margin-bottom: 10px;
}

.add-ai-btn {
  background: rgba(78, 205, 196, 0.2);
  border: 1px solid #4ECDC4;
  color: #4ECDC4;
  border-radius: 8px;
  padding: 6px 12px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.add-ai-btn:hover:not(:disabled) {
  background: rgba(78, 205, 196, 0.3);
}

.add-ai-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.actions-section {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
  flex-wrap: wrap;
  justify-content: center;
}

.btn {
  padding: 12px 30px;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.btn-ready {
  background: linear-gradient(135deg, #2ECC71, #27AE60);
  color: white;
}

.btn-ai {
  background: linear-gradient(135deg, #4ECDC4, #44A08D);
  color: white;
}

.btn-cancel-ready {
  background: linear-gradient(135deg, #E67E22, #D35400);
  color: white;
}

.btn-start {
  background: linear-gradient(135deg, #3498DB, #2980B9);
  color: white;
  padding: 15px 40px;
  font-size: 18px;
}

.btn-leave {
  background: linear-gradient(135deg, #E74C3C, #C0392B);
  color: white;
}

.btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.rules-hint {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  border-radius: 15px;
  padding: 20px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  max-width: 500px;
  width: 100%;
}

.hint-text {
  color: rgba(255, 255, 255, 0.8);
  text-align: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.hint-text:last-child {
  margin-bottom: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .players-grid {
    grid-template-columns: 1fr;
    max-width: 300px;
    margin: 0 auto;
  }
  
  .actions-section {
    flex-direction: column;
    align-items: center;
  }
  
  .btn {
    width: 200px;
  }
}</style>